<template>
    <div>
        <van-divider>导入导出</van-divider>
        <van-form>
            <div style="margin: 16px;">
                <van-button round block type="primary" @click="showImport = true">
                    导入
                </van-button>
            </div>
            <div style="margin: 16px;">
                <van-button round block type="primary" @click="exportJson">
                    导出
                </van-button>
            </div>
        </van-form>
        <van-dialog v-model:show="showExport" title="导出JSON" show-cancel-button="false" @confirm="copytoClipboard">
            <van-field v-model="bookmarket" rows="1" type="textarea" placeholder="请输入JSON" />
        </van-dialog>
        <van-dialog v-model:show="showImport" title="导入JSON" show-cancel-button="false" @confirm="importJson">
            <van-field v-model="bookmarket" rows="1" type="textarea" placeholder="请输入JSON" />
        </van-dialog>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { getAllBookmarks, updateBookmark, getBookmarkById, addBookmark } from '@/utils/api';
import { showNotify } from 'vant';
const bookmarket = ref('');
const showExport = ref(false);
const showImport = ref(false);
const exportJson = () => {
    getBookmark();
}

const importJson = () => {
    updateBookmarks()
}

function getBookmark() {
    getAllBookmarks().then(res => {
        bookmarket.value = JSON.stringify(res);
        showExport.value = true;
    })
}

function updateBookmarks() {
    const json = bookmarket.value;
    const bookmarks = JSON.parse(json);
    for (let i = 0; i < bookmarks.length; i++) {
        // 判断是否存在 id
        if (bookmarks[i].id) {
            // 查询是否存在
            getBookmarkById(bookmarks[i].id).then(res => {
                console.log(res);
                if (res != null) {
                    updateBookmark(bookmarks[i]).then(res => {
                        console.log('更新成功');
                    }).catch(err => {
                        console.log('更新失败');
                    });
                } else {
                    addBookmark(bookmarks[i]).then(res => {
                        console.log('创建成功');
                    }).catch(err => {
                        console.log('创建失败');
                    });
                }
            });
        } else {
            addBookmark(bookmarks[i]).then(res => {
                console.log('创建成功');
            }).catch(err => {
                console.log('创建失败');
            });
        }
    }

    showNotify({ type: 'success', message: '处理完成' });
}



function copytoClipboard() {
    // 拷贝 bookmarket 到剪切板
    navigator.clipboard.writeText(bookmarket.value)
        .then(() => {
            showNotify({ type: 'success', message: '复制成功' });
            bookmarket.value = '';
        }).catch((err) => {
            showNotify({ type: 'error', message: '复制失败' });
            bookmarket.value = '';
        });

}

</script>

<style></style>